package com.gucheng.springframework.beans.factory.support;

import com.gucheng.springframework.beans.BeansException;
import com.gucheng.springframework.beans.factory.config.BeanDefinition;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.NoOp;

import java.lang.reflect.Constructor;

public class CglibSubclassingInstantiationStrategy implements InstantiationStrategy {
    @Override
    public Object instantiate(BeanDefinition beanDefinition, String beanName, Constructor ctor, Object[] args) throws BeansException {
        // 创建Enhancer对象
        Enhancer enhancer = new Enhancer();
        // 设置父类beanDefinition.getBeanClass()
        enhancer.setSuperclass(beanDefinition.getBeanClass());
        // 设置回调函数
        enhancer.setCallback(new NoOp(){
            @Override
            public int hashCode() {
                return super.hashCode();
            }
        });
        // 创建增强对象(空参)
        if (null == ctor) return enhancer.create();
        //有参
        return enhancer.create(ctor.getParameterTypes(), args);
    }
}
